# -*-coding: utf-8 -*-
"""
    @Theme   : 
    @Time    : 2024/7/10 12:09
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
from flask import Blueprint, request, render_template, jsonify, current_app, g
from werkzeug.security import check_password_hash, generate_password_hash

from qanda.utils import generate_session, login_required
from qanda.models_business import db_utils


auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        body = request.json
        user = body.get('user', '')
        password = body.get('password', '')

        if not all([user, password]):
            return jsonify({'success': False, 'reason': '用户名和密码不能为空！'})

        user_info = db_utils.mongo.get_user_info(user)
        if not user_info['success']:
            return jsonify(user_info)

        password_hash = user_info['user_info']['password_hash']
        if not check_password_hash(password_hash, password):
            return jsonify({'success': False, 'reason': '用户名与密码不匹配！'})

        session_id, session_data = generate_session(str(user_info['user_info']['_id']),
                                                    user, expire_days=current_app.config['SESSION_EXPIRE_DAYS'])
        res = jsonify({'success': True})
        res.set_cookie('session_id', session_id,
                       max_age=current_app.config['SESSION_EXPIRE_DAYS'] * 24 * 3600)
        db_utils.redis.save_session(session_id, session_data)
        return res


@auth_bp.route('/logout', methods=['POST'])
@login_required
def logout():
    db_utils.redis.delete_session(request.cookies.get('session_id'))
    res = jsonify({'success': True})
    res.delete_cookie('session_id')
    return res


@auth_bp.route('/register', methods=['POST'])
def register():
    body = request.json
    user = body.get('user', '')
    password = body.get('password', '')

    if not all([user, password]):
        return jsonify({'success': False, 'reason': '用户名和密码不能为空！'})

    with db_utils.bloom.bloom_lock(user):
        if db_utils.bloom.check_duplicate(user):
            return jsonify({'success': False, 'reason': '用户名已被注册！请更换'})
        db_utils.bloom.set_key(user)

    password_hash = generate_password_hash(password)
    user_id = db_utils.mongo.save_user_info(user, password_hash)
    session_id, session_data = generate_session(user_id, user, current_app.config['SESSION_EXPIRE_DAYS'])

    db_utils.redis.save_session(session_id, session_data)
    res = jsonify({'success': True})
    res.set_cookie('session_id', session_id,
                   max_age=current_app.config['SESSION_EXPIRE_DAYS'] * 24 * 3600)
    return res
